package org.wk.user.service;

import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wk.account.service.SubAccountService;
import org.wk.account.view.LingExchangeCNYVo;
import org.wk.common.jpush.PushService;
import org.wk.common.view.SysNoticeDTO;
import org.wk.core.common.exception.ExceptionCode;
import org.wk.core.common.view.PageVo;
import org.wk.core.common.view.ResponseVo;
import org.wk.core.web.exception.GeneralException;
import org.wk.user.dao.ApplyVipDao;
import org.wk.user.dao.ApplyVipLogDao;
import org.wk.user.dao.UserDao;
import org.wk.user.dao.UserPromoteRelationDao;
import org.wk.user.domain.ApplyVip;
import org.wk.user.domain.ApplyVipLog;
import org.wk.user.domain.User;
import org.wk.user.domain.UserPromoteRelation;
import org.wk.user.enums.IdentityType;
import org.wk.user.enums.VerifyStatus;
import org.wk.user.view.ApplyVipVo;
import org.wk.user.view.UserVo;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ApplyVipServiceImpl
 * @Description VIP申请管理 -PC
 * @Author ZhaoPing'an
 * @Date 2018/6/1 15:40
 */
@Transactional(rollbackOn = Exception.class)
@Service
public class ApplyVipServiceImpl implements ApplyVipService{

    @Autowired
    private ApplyVipDao applyVipDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ApplyVipLogDao applyVipLogDao;
    @Autowired
    private SubAccountService subAccountService;
    @Autowired
    private PushService pushService;
    @Autowired
    private UserPromoteRelationDao userPromoteRelationDao;

    /**
     * @Description VIP申请列表
     * @Param [params]
     * @author ZhaoPing'an
     * @Date 2018/6/1 16:12
     */
    @Override
    public PageVo findApplyVipListPage(Map<String, Object> params) {
        String temp = (String)params.get("page");
        Integer pageNo = temp==null?0:Integer.parseInt(temp)-1;
        temp = (String) params.get("limit");
        Integer pageSize = temp==null?10:Integer.parseInt(temp);
        String realName = (String)params.get("realName");
        String mobilePhone = (String)params.get("mobilePhone");
        String startDate = (String) params.get("startDate");
        String endDate = (String)params.get("endDate");
        String status = (String)params.get("status");
        Page<ApplyVip> page = applyVipDao.findAll(new Specification<ApplyVip>() {
            @Override
            public Predicate toPredicate(Root<ApplyVip> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(!StringUtils.isEmpty(realName)){
                    list.add(criteriaBuilder.like(root.get("realName").as(String.class), "%"+realName+"%"));
                }
                if(!StringUtils.isEmpty(mobilePhone)){
                    list.add(criteriaBuilder.like(root.get("mobilePhone").as(String.class), "%"+mobilePhone+"%"));
                }
                if (!StringUtils.isEmpty(startDate)){
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), org.wk.core.common.tool.StringUtils.strToDate(startDate)));
                }
                if (!StringUtils.isEmpty(endDate)){
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), org.wk.core.common.tool.StringUtils.strToDate(endDate)));
                }
                if (!StringUtils.isEmpty(status)){
                    list.add(criteriaBuilder.equal(root.get("verifyStatusCode"), status));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, PageRequest.of(pageNo,pageSize,new Sort(Sort.Direction.DESC,"createTime")));
        List<ApplyVip> applys = page.getContent();
        /*List<String> userIds = new ArrayList<>();
        for (int i = 0; i < applys.size(); i++) {
            userIds.add(applys.get(i).getUserId());
        }
        List<User> users = userDao.findByIdIn(userIds);*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        List<ApplyVipVo> result = new ArrayList<>();
        User relationUser, sellerUser,user;
        for (ApplyVip apply: applys) {
            ApplyVipVo applyVipVo = new ApplyVipVo();
            BeanUtils.copyProperties(apply,applyVipVo);
            applyVipVo.setCreateTime(sdf.format(apply.getCreateTime()));
            //审批人信息
            relationUser = userDao.getOne(applyVipVo.getRelationId());
            applyVipVo.setRelationName(relationUser.getUserName());
            applyVipVo.setRelationTel(relationUser.getMobileNumber());
            applyVipVo.setRelationStatus(VerifyStatus.containsCode(applyVipVo.getRelationStatus()).getName());
            //二级审批人信息
            if (null != applyVipVo.getSellerId()){
                sellerUser = userDao.getOne(applyVipVo.getSellerId());
                applyVipVo.setSellerName(sellerUser.getUserName());
                applyVipVo.setSellerTel(sellerUser.getMobileNumber());
                applyVipVo.setSellerStatus(VerifyStatus.containsCode(applyVipVo.getSellerStatus()).getName());
            }
            //申请人信息
            user = userDao.getOne(applyVipVo.getUserId());
            applyVipVo.setRealName(user.getUserName());
            applyVipVo.setMobilePhone(user.getMobileNumber());
            result.add(applyVipVo);
        }
        PageVo pageVo = new PageVo<ApplyVipVo>();
        pageVo.setTotal(page.getTotalElements());
        pageVo.setPageNo(++pageNo);
        pageVo.setPageSize(pageSize);
        pageVo.setResult(result);
        pageVo.setTotalPages(page.getTotalPages());
        return pageVo;
    }

    /**
     * @Description VIP申请详情
     * @Param [applyId]
     * @author ZhaoPing'an
     * @Date 2018/6/2 11:13
     */
    @Override
    public ApplyVipVo findApplyVipInfo(String applyId) {
        ApplyVipVo applyInfo = new ApplyVipVo();
        ApplyVip result = applyVipDao.getOne(applyId);
        User user = userDao.getOne(result.getUserId());
        BeanUtils.copyProperties(result,applyInfo);
        applyInfo.setReferralCode(user.getReferralCode());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        applyInfo.setCreateTime(sdf.format(result.getCreateTime()));

        return applyInfo;
    }

    /**
     * @Description 初审通过
     * @Param [id]
     * @author ZhaoPing'an
     * @Date 2018/6/2 17:17
     */
    @Override
    public void firstVerify(String id) {

        ApplyVip applyVip = applyVipDao.getOne(id);
        if (!VerifyStatus.WAIT_VERIFY.getCode().equals(applyVip.getVerifyStatusCode())) {
            throw new GeneralException(ExceptionCode.ex_base_001);
        }
        applyVip.setVerifyStatusCode(VerifyStatus.FIRST_VERIFY_PASS.getCode());
        applyVip.setVerifyStatusName(VerifyStatus.FIRST_VERIFY_PASS.getName());
        applyVipDao.update(applyVip);
        // 保存初审记录
        saveLog(id,VerifyStatus.FIRST_VERIFY_PASS,null);
    }

    /**
     * @Description 初审不通过
     * @Param [id]
     * @author ZhaoPing'an
     * @Date 2018/6/4 12:15
     */
    @Override
    public void refuseFirstVerify(ApplyVipVo applyVip) {
        String applyId = applyVip.getId();
        ApplyVip applyVipEntity = applyVipDao.getOne(applyId);
        if (!VerifyStatus.WAIT_VERIFY.getCode().equals(applyVip.getVerifyStatusCode())) {
            throw new GeneralException(ExceptionCode.ex_base_001);
        }
        applyVipEntity.setVerifyStatusCode(VerifyStatus.FIRST_VERIFY_FAIL.getCode());
        applyVipEntity.setVerifyStatusName(VerifyStatus.FIRST_VERIFY_FAIL.getName());
        applyVipDao.update(applyVipEntity);

        // 保存初审记录
        saveLog(applyId,VerifyStatus.FIRST_VERIFY_FAIL, applyVip.getRefuseReason());
        // 推送？ 短信？
        Map<String,String> pushExt = new HashMap<>(2);
        pushExt.put("content_type","sys_notice");
        SysNoticeDTO sysNoticeDTO = new SysNoticeDTO();
        sysNoticeDTO.setTitle("系统通知");
        sysNoticeDTO.setContent("hin遗憾，您的VIP申请失败，原因:"+applyVip.getRefuseReason());
        pushExt.put("content",JSONObject.toJSONString(sysNoticeDTO));
        // 推送？ 短信？
        pushService.pushNotification("VIP申请失败",pushExt,applyVipEntity.getUserId());
    }

    /**
     * @Description 终审通过
     * @Param [id]
     * @author ZhaoPing'an
     * @Date 2018/6/4 12:17
     */
    @Override
    public ResponseVo finalVerify(String id) {
        ApplyVip applyVip = applyVipDao.getOne(id);
        //修改申请状态,提升用户等级
        applyVip.setRelationStatus(VerifyStatus.FINAL_VERIFY_PASS.getCode());
        //修改推荐关系
        UserPromoteRelation userPromoteRelation = userPromoteRelationDao.findByParentIdAndUserId(applyVip.getRelationId(),applyVip.getUserId());
        userPromoteRelation.setStatus("Y");
        userPromoteRelationDao.update(userPromoteRelation);
        if (null != applyVip.getSellerId()){
            applyVip.setSellerStatus(VerifyStatus.FINAL_VERIFY_PASS.getCode());
            userPromoteRelation = userPromoteRelationDao.findByParentIdAndUserId(applyVip.getSellerId(),applyVip.getUserId());
            userPromoteRelation.setStatus("S");
            userPromoteRelationDao.update(userPromoteRelation);
        }
        applyVipDao.update(applyVip);
        User user = userDao.getOne(applyVip.getUserId());
        user.setIdentityCode(applyVip.getIdentityCode());
        user.setIdentityName(applyVip.getIdentityName());
        userDao.update(user);
        return ResponseVo.success();
    }

    /**
     * @Description 终审不通过
     * @Param [id]
     * @author ZhaoPing'an
     * @Date 2018/6/4 12:17
     */
    @Override
    public void refuseFinalVerify(ApplyVip applyVip) {
        String applyId = applyVip.getId();
        applyVip = applyVipDao.getOne(applyId);
        applyVip.setRelationStatus(VerifyStatus.FINAL_VERIFY_FAIL.getCode());
        if (null != applyVip.getSellerId()){
             applyVip.setSellerStatus(VerifyStatus.FINAL_VERIFY_FAIL.getCode());
        }
        applyVipDao.update(applyVip);
    }

    private void saveLog(String applyVipId, VerifyStatus verifyStatus, String remarks) {
        ApplyVipLog applyVipLog = new ApplyVipLog();
        applyVipLog.setApplyId(applyVipId);
        applyVipLog.setStatusCode(verifyStatus.getCode());
        applyVipLog.setStatusName(verifyStatus.getName());
        applyVipLog.setRemarks(remarks);
        applyVipLogDao.save(applyVipLog);
    }



}
